import 'dart:io';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../services/file_service.dart';
import '../providers/map_editor_provider.dart';
import '../models/map_models.dart';
import 'rect_image.dart';

class ImageImportDialog extends StatefulWidget {
  const ImageImportDialog({super.key});

  @override
  State<ImageImportDialog> createState() => _ImageImportDialogState();
}

class _ImageImportDialogState extends State<ImageImportDialog> {
  ImageFileInfo? _selectedImage;
  TileSetSuggestion? _suggestion;
  bool _isLoading = false;
  final _nameController = TextEditingController();
  final _tileWidthController = TextEditingController(text: '32');
  final _tileHeightController = TextEditingController(text: '32');
  final _pathController = TextEditingController();

  @override
  void dispose() {
    _nameController.dispose();
    _tileWidthController.dispose();
    _tileHeightController.dispose();
    _pathController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('导入图片作为图块集'),
      content: SizedBox(
        width: 500,
        height: 600,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 路径输入框
            TextField(
              controller: _pathController,
              decoration: InputDecoration(
                labelText: '图片路径',
                hintText: '输入图片文件路径或点击浏览...',
                border: const OutlineInputBorder(),
                isDense: true,
                suffixIcon: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    IconButton(
                      onPressed: _isLoading ? null : _selectImage,
                      icon: const Icon(Icons.folder_open),
                      tooltip: '浏览',
                      iconSize: 20,
                    ),
                    IconButton(
                      onPressed: _isLoading ? null : _loadFromPath,
                      icon: const Icon(Icons.check),
                      tooltip: '加载',
                      iconSize: 20,
                    ),
                  ],
                ),
              ),
              onChanged: (_) => setState(() {}),
              onSubmitted: (_) => _loadFromPath(),
            ),
            
            const SizedBox(height: 8),
            
            // 选择图片按钮
            ElevatedButton.icon(
              onPressed: _isLoading ? null : _selectImage,
              icon: const Icon(Icons.image),
              label: Text(_selectedImage == null ? '选择图片' : '重新选择'),
            ),
            
            const SizedBox(height: 16),
            
            // 图片信息显示
            if (_selectedImage != null) ...[
              _buildImageInfo(),
              const SizedBox(height: 16),
              
              // 图块集设置
              _buildTileSetSettings(),
              const SizedBox(height: 16),
              
              // 预览信息
              if (_suggestion != null)
                _buildSuggestionPreview(),
            ],
            
            if (_isLoading)
              const Center(
                child: CircularProgressIndicator(),
              ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(),
          child: const Text('取消'),
        ),
        ElevatedButton(
          onPressed: _selectedImage != null && _suggestion != null && !_isLoading
              ? _importTileSet
              : null,
          child: const Text('导入'),
        ),
      ],
    );
  }

  Widget _buildImageInfo() {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey[300]!),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '图片信息',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 8),
          Text('文件名: ${_selectedImage!.name}'),
          Text('尺寸: ${_selectedImage!.width} x ${_selectedImage!.height}'),
          Text('格式: ${_selectedImage!.format}'),
          const SizedBox(height: 8),
          Text(
            '路径: ${_selectedImage!.path}',
            style: const TextStyle(fontSize: 12, color: Colors.grey),
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ),
    );
  }

  Widget _buildTileSetSettings() {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey[300]!),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '图块集设置',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 12),
          
          // 名称输入
          TextField(
            controller: _nameController,
            decoration: const InputDecoration(
              labelText: '图块集名称',
              border: OutlineInputBorder(),
              isDense: true,
            ),
            onChanged: (_) => _updateSuggestion(),
          ),
          const SizedBox(height: 12),
          
          // 图块尺寸设置
          Row(
            children: [
              Expanded(
                child: TextField(
                  controller: _tileWidthController,
                  decoration: const InputDecoration(
                    labelText: '图块宽度',
                    border: OutlineInputBorder(),
                    isDense: true,
                  ),
                  keyboardType: TextInputType.number,
                  onChanged: (_) => _updateSuggestion(),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: TextField(
                  controller: _tileHeightController,
                  decoration: const InputDecoration(
                    labelText: '图块高度',
                    border: OutlineInputBorder(),
                    isDense: true,
                  ),
                  keyboardType: TextInputType.number,
                  onChanged: (_) => _updateSuggestion(),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildSuggestionPreview() {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.green[300]!),
        borderRadius: BorderRadius.circular(8),
        color: Colors.green[50],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Text(
                '预览',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              const Spacer(),
              Text(
                '${_suggestion!.columns} 列 × ${_suggestion!.rows} 行 (${_suggestion!.tileCount} 个图块)',
                style: const TextStyle(fontSize: 12, color: Colors.black54),
              ),
            ],
          ),
          const SizedBox(height: 12),
          
          // 图块预览网格
          Container(
            height: 120,
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey[300]!),
              borderRadius: BorderRadius.circular(4),
            ),
            child: _suggestion!.tileCount == 0
                ? const Center(
                    child: Text(
                      '无法生成有效图块，请检查图块尺寸',
                      style: TextStyle(color: Colors.red, fontSize: 12),
                    ),
                  )
                : _buildTilePreviewGrid(),
          ),
          
          const SizedBox(height: 8),
          if (_suggestion!.imageWidth % _suggestion!.tileWidth != 0 ||
              _suggestion!.imageHeight % _suggestion!.tileHeight != 0)
            Text(
              '提示: 图片尺寸不能被图块尺寸整除，边缘部分将被裁切',
              style: TextStyle(color: Colors.orange[700], fontSize: 11),
            ),
        ],
      ),
    );
  }

  Widget _buildTilePreviewGrid() {
    if (_selectedImage == null || _suggestion == null) {
      return const SizedBox.shrink();
    }

    // 参考Android实现，显示所有可见的图块
    // 对于大图像集（如16x16=256个图块），我们需要合理限制显示数量
    final maxDisplayColumns = 8; // 最多显示8列，保持界面美观
    final maxDisplayRows = 6; // 最多显示6行
    final maxTilesToShow = maxDisplayColumns * maxDisplayRows; // 最多48个图块
    
    final tilesToShow = _suggestion!.tileCount > maxTilesToShow 
        ? maxTilesToShow 
        : _suggestion!.tileCount;
    
    // 计算实际显示的网格列数
    final actualColumns = _suggestion!.columns > maxDisplayColumns 
        ? maxDisplayColumns 
        : _suggestion!.columns;

    return Padding(
      padding: const EdgeInsets.all(4),
      child: Column(
        children: [
          Expanded(
            child: GridView.builder(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: actualColumns,
                crossAxisSpacing: 1,
                mainAxisSpacing: 1,
                childAspectRatio: 1,
              ),
              itemCount: tilesToShow,
              itemBuilder: (context, index) {
                return _buildPreviewTile(index);
              },
            ),
          ),
          if (_suggestion!.tileCount > maxTilesToShow)
            Padding(
              padding: const EdgeInsets.only(top: 4),
              child: Text(
                '预览前 $maxTilesToShow 个图块，总共 ${_suggestion!.tileCount} 个',
                style: const TextStyle(fontSize: 10, color: Colors.black54),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildPreviewTile(int tileIndex) {
    if (_selectedImage == null || _suggestion == null) {
      return const SizedBox.shrink();
    }

    // 计算图块在图片中的位置
    final row = tileIndex ~/ _suggestion!.columns;
    final col = tileIndex % _suggestion!.columns;
    final sourceX = col * _suggestion!.tileWidth.toDouble();
    final sourceY = row * _suggestion!.tileHeight.toDouble();

    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey[400]!, width: 0.5),
        borderRadius: BorderRadius.circular(2),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(1.5),
        child: RectImage.fromImage(
          imagePath: _selectedImage!.path,
          sourceX: sourceX,
          sourceY: sourceY,
          sourceWidth: _suggestion!.tileWidth.toDouble(),
          sourceHeight: _suggestion!.tileHeight.toDouble(),
          fit: BoxFit.cover,
          errorWidget: Container(
            color: Colors.grey[200],
            child: Center(
              child: Text(
                '$tileIndex',
                style: const TextStyle(
                  fontSize: 8,
                  color: Colors.black54,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Future<void> _selectImage() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final imageInfo = await FileService.pickImageFile();
      if (imageInfo != null) {
        setState(() {
          _selectedImage = imageInfo;
          _nameController.text = imageInfo.name;
          _pathController.text = imageInfo.path;
        });
        _updateSuggestion();
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('选择图片失败: $e')),
        );
      }
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _loadFromPath() async {
    final path = _pathController.text.trim();
    if (path.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请输入图片路径')),
      );
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      final imageInfo = await FileService.analyzeImageFile(path);
      if (imageInfo != null) {
        setState(() {
          _selectedImage = imageInfo;
          _nameController.text = imageInfo.name;
        });
        _updateSuggestion();
        
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('图片加载成功')),
          );
        }
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('无法加载图片，请检查路径是否正确')),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载图片失败: $e')),
        );
      }
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _updateSuggestion() {
    if (_selectedImage == null) return;

    final tileWidth = int.tryParse(_tileWidthController.text) ?? 32;
    final tileHeight = int.tryParse(_tileHeightController.text) ?? 32;

    if (tileWidth <= 0 || tileHeight <= 0) {
      setState(() {
        _suggestion = null;
      });
      return;
    }

    final suggestion = FileService.suggestTileSetFromImage(
      _selectedImage!,
      tileWidth,
      tileHeight,
    );

    setState(() {
      _suggestion = TileSetSuggestion(
        name: _nameController.text.isEmpty ? suggestion.name : _nameController.text,
        imagePath: suggestion.imagePath,
        tileWidth: suggestion.tileWidth,
        tileHeight: suggestion.tileHeight,
        columns: suggestion.columns,
        rows: suggestion.rows,
        tileCount: suggestion.tileCount,
        imageWidth: suggestion.imageWidth,
        imageHeight: suggestion.imageHeight,
        imageFormat: suggestion.imageFormat,
      );
    });
  }

  void _importTileSet() {
    if (_suggestion == null || _suggestion!.tileCount == 0) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('无法创建有效的图块集')),
      );
      return;
    }

    final provider = Provider.of<MapEditorProvider>(context, listen: false);
    
    // 计算firstGid
    int firstGid = 10; // 基础图块占用1-9
    if (provider.hasMap) {
      for (final tileSet in provider.currentMap!.tileSets) {
        final maxGid = tileSet.firstGid + tileSet.tileCount;
        if (maxGid >= firstGid) {
          firstGid = maxGid;
        }
      }
    }

    final tileSet = TileSet(
      name: _suggestion!.name,
      imagePath: _suggestion!.imagePath,
      tileWidth: _suggestion!.tileWidth,
      tileHeight: _suggestion!.tileHeight,
      tileCount: _suggestion!.tileCount,
      columns: _suggestion!.columns,
      firstGid: firstGid,
    );

    if (provider.hasMap) {
      provider.addTileSet(tileSet);
      Navigator.of(context).pop();
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('图块集 "${tileSet.name}" 已添加')),
      );
    } else {
      Navigator.of(context).pop();
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请先创建或打开一个地图')),
      );
    }
  }
}